package com.innovation.wjrpc.handle;

import com.innovation.wjrpc.codec.Decoder;
import com.innovation.wjrpc.codec.impl.JSONDecoder;
import com.innovation.wjrpc.protocol.Response;
import com.innovation.wjrpc.result.ResultsMap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @author innoyiya
 * @date 2021/9/8 11:17
 */
@Slf4j
@Data
public class NettyClientHandle extends SimpleChannelInboundHandler<ByteBuf> {

    private ChannelHandlerContext ctx;
    private Decoder decoder = new JSONDecoder();

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        this.ctx = ctx;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        Response response = decoder.decode(bytes, Response.class);
        //log.info("channelRead0 run " + response.toString());
        ResultsMap.updateResult(response.getId(), response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
